
package com.cuitrip.business.user;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.login.proxy.VcodeProxy;
import com.cuitrip.component.LoadingButton;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.track.TrackUtil;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.jakewharton.rxbinding.widget.TextViewTextChangeEvent;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.proxy.ApiProxy;
import com.lab.network.proxy.ApiProxyBuilder;
import com.lab.network.proxy.ApiProxyCallBack;
import com.lab.rx.BaseSubscriber;
import com.lab.utils.Utils;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.Bind;
import butterknife.OnClick;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.CountryPage;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;

/**
 *
 */
public class CertPhoneActivity extends CustomUiFragmentActivity implements CountryPage.OnResult {
    boolean isEnterPhone;
    @Bind(R.id.editView)
    EditText editPhone;
    @Bind(R.id.phoneButton)
    LoadingButton phoneButton;
    @Bind(R.id.resendView)
    TextView resendView;
    @Bind(R.id.tipView)
    TextView tipView;
    @Bind(R.id.phoneHolder)
    TextView phoneHolder;
    @Bind(R.id.countryCode)
    TextView countryCodeView;
    @Bind(R.id.divider)
    View divider;
    String phone = "";
    Subscriber<TextViewTextChangeEvent> subscriber = new BaseSubscriber<TextViewTextChangeEvent>() {
        @Override
        public void onNext(TextViewTextChangeEvent event) {
            boolean enable;
            String value;
            if (event.text() == null) {
                value = null;
            } else {
                value = event.text().toString();
            }
            if (isEnterPhone) {
                enable = value.length() >= 6;
            } else {
                enable = !TextUtils.isEmpty(value);
            }
            phoneButton.setEnabled(enable);
        }
    };
    Subscriber<Long> timeSubscriber;
    private String currentId;
    private String countryCode;
    private HashMap<String, String> countryRules;
    private static final int TIMING_COUNT = 60;
    ApiProxy apiProxy;
    private IProxyCallback verifyCallBack = new ApiProxyCallBack<Object>() {
        @Override
        public void doPreWork(CtApiResponse response) {
            phoneButton.hideLoading();
        }

        @Override
        public boolean onSuccess(Object data, CtApiResponse response) {
            Intent intent = new Intent();
            String value;
            if (countryCode !=null){
                value="+"+ countryCode +" "+phone;
            }else{
                value=phone;
            }
            intent.putExtra(ShowCertInfoFragment.RESULT_DATA, value);
            setResult(RESULT_OK, intent);
            finish();
            TrackUtil.trackScreenName("/user/verification/phone/verified");
            return super.onSuccess(data, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            phoneButton.setText(R.string.operation_verify);
            phoneHolder.setText(response.msg);
            phoneHolder.setSelected(true);
            return super.onFaild(response);
        }
    };
    private IProxyCallback sendCallBack = new ApiProxyCallBack<Object>(){
        @Override
        public void doPreWork(CtApiResponse response) {
            phoneButton.hideLoading();
        }

        @Override
        public boolean onSuccess(Object data, CtApiResponse response) {
            if (!isEnterPhone) {
                return false;
            }
            isEnterPhone = false;
            rendView();
            return super.onSuccess(data, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            phoneButton.setText(R.string.verification_code_send);
            phoneHolder.setText(response.msg);
            phoneHolder.setSelected(true);
            return super.onFaild(response);
        }
    };
    private int time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_cert_phone);
        ButterKnife.bind(this);
        apiProxy = ApiProxyBuilder.getBuilder().addApiCallBack(ApiManager.SEND_VERIFY_SMS, sendCallBack)
                .addApiCallBack(ApiManager.VERIFY_PHONE, verifyCallBack).build();
        RxTextView
                .textChangeEvents(editPhone)
                .subscribe(subscriber);
        isEnterPhone = true;
        countryCode = VcodeProxy.getInstance().getCurrentCountryCode(this);
        setCountryCode(countryCode);
        rendView();
    }

    /**
     * 渲染视图
     */
    private void rendView() {
        if (isEnterPhone) {
            //第一个阶段输入手机号
            tipView.setText(R.string.phone_verify_desc);
            phoneHolder.setText(R.string.phone_number_desc);
            phoneHolder.setSelected(false);
            editPhone.setHint(R.string.phone);
            editPhone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100)});
            editPhone.setText(phone);
            editPhone.setSelection(phone != null ? phone.length() : 0);
            phoneButton.setText(R.string.verification_code_send);
            resendView.setVisibility(View.GONE);
            countryCodeView.setVisibility(View.VISIBLE);
            divider.setVisibility(View.VISIBLE);
        } else {
            //第二个阶段输入Vcode
            editPhone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
            tipView.setText(getString(R.string.verification_code_send_feedback_suc, countryCodeView.getText().toString() +" "+ phone));
            editPhone.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
            phoneHolder.setText(R.string.verification_code_desc_1);
            phoneHolder.setSelected(false);
            editPhone.setHint(R.string.verification_code);
            editPhone.setText("");
            countryCodeView.setVisibility(View.GONE);
            divider.setVisibility(View.GONE);
            phoneButton.setText(R.string.operation_verify);
            setResendText();
            resendView.setVisibility(View.VISIBLE);
        }
    }

    private void setResendText() {
        String noSMS =getString(R.string.phone_not_receive);
        String resend =getString(R.string.operation_resend);
        SpannableString ss=new SpannableString(noSMS +" "+resend);
        ss.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                resend();
            }
        }, ss.length() - resend.length(), ss.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        ss.setSpan(new ForegroundColorSpan(ResourceUtil.getThemeColor()),  ss.length() - resend.length(), ss.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        resendView.setText(ss);
        resendView.setClickable(true);
        resendView.setMovementMethod(new LinkMovementMethod(){
            @Override
            protected boolean down(TextView widget, Spannable buffer) {
                return super.down(widget, buffer);
            }
        });
    }

    /**
     * 更改countryCode的显示，如{@link #isEnterPhone}为true，更改区号，否则隐藏区号显示
     *
     * @param countryCode
     */
    private void setCountryCode(String countryCode) {
        if (isEnterPhone) {
            this.countryCode = countryCode;
            divider.setVisibility(View.VISIBLE);
            countryCodeView.setVisibility(View.VISIBLE);
            String value;
            if (countryCode.startsWith("+") == false) {
                value = "+" + countryCode;
            } else {
                value = countryCode;
            }
            countryCodeView.setText(value);
        } else {
            divider.setVisibility(View.GONE);
            countryCodeView.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.countryCode)
    public void selectCountryCode() {
        CountryPage countryPage = new CountryPage();
        countryPage.setCountryId(currentId);
        countryPage.setCountryRuls(countryRules);
        countryPage.setOnResultListener(CertPhoneActivity.this);
        countryPage.showForResult(CertPhoneActivity.this, null);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        subscriber.unsubscribe();
    }

    void resend() {
        //set phoneHolder
        phoneHolder.setText(isEnterPhone ? R.string.phone_number_desc : R.string.verification_code_desc_1);
        phoneHolder.setSelected(false);
        //移除输入法
        Utils.hideSoftInputMethod(this);
        if (phoneButton.isLoading()) {
            return;
        }
        phoneButton.showLoading();
        UserBusiness.sendVerifySMS(apiProxy, countryCode,phone);
        time = TIMING_COUNT;
        timeSubscriber = new BaseSubscriber<Long>() {
            @Override
            public void onStart() {
                resendView.setEnabled(false);
            }

            @Override
            public void onCompleted() {
                setResendText();
                resendView.setEnabled(true);
                this.unsubscribe();
            }

            @Override
            public void onNext(Long number) {
                if (time > 0) {
                    resendView.setText(getString(R.string.verification_code_resend, time));
                    time--;
                }
            }
        };
        Observable//
                .interval(1, TimeUnit.SECONDS).take(TIMING_COUNT+1)//
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(timeSubscriber);
    }

    public void verify(){
        //set phoneHolder
        phoneHolder.setText(R.string.verification_code_desc_1);
        phoneHolder.setSelected(false);
        //移除输入法
        Utils.hideSoftInputMethod(this);
        if (phoneButton.isLoading()) {
            return;
        }
        phoneButton.showLoading();
        UserBusiness.verifySMS(apiProxy, countryCode, phone,editPhone.getText().toString());
    }

    @OnClick(R.id.button)
    void onButtonClick() {
        if (!phoneButton.isEnabled()){
            return;
        }
        if (isEnterPhone) {
            phone = editPhone.getText().toString();
            TrackUtil.trackScreenName("/user/verification/phone/set/code");
            resend();
        } else {
            //第二个阶段输入Vcode
            verify();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            onTopbarLeftPress();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onTopbarLeftPress() {
        if (isEnterPhone){
            //正在输入手机 -> 退出
            finish();
        } else {
            //正在输入Vcode->推到上一步
            isEnterPhone =true;
            rendView();
        }
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = getString(R.string.phone_verify);
        return config;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(IS_ENTER_PHONE,isEnterPhone);
    }

    public static final String IS_ENTER_PHONE = "IS_ENTER_PHONE";
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        apiProxy = ApiProxyBuilder.getBuilder().addApiCallBack(ApiManager.SEND_VERIFY_SMS, sendCallBack)
                .addApiCallBack(ApiManager.VERIFY_PHONE, verifyCallBack).build();
        RxTextView
                .textChangeEvents(editPhone)
                .subscribe(subscriber);
        isEnterPhone =  savedInstanceState.getBoolean(IS_ENTER_PHONE);
        countryCode = VcodeProxy.getInstance().getCurrentCountryCode(this);
        setCountryCode(countryCode);
        rendView();
    }

    @Override
    public void onResult(HashMap<String, Object> data) {
        if (data != null) {
            int page = (Integer) data.get("page");
            if (page == 1) {
                // 国家列表返回
                currentId = (String) data.get("id");
                countryRules = (HashMap<String, String>) data.get("rules");
                String[] country = SMSSDK.getCountry(currentId);
                if (country != null && country.length >= 2) {
                    countryCode = country[1];
                    setCountryCode(countryCode);
                }
//                checkPhoneNum(getPhoneNum().getText().toString().trim(), currentCode);
            }
        }
    }
}
